package com.activemq.demo.activemq_service.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import jakarta.jms.JMSException;
import jakarta.jms.Message;

@Service
public class MessageConsumerService {

    private static final Logger logger = LoggerFactory.getLogger(MessageConsumerService.class);

    private final MessageProcessingService messageProcessingService;

    public MessageConsumerService(MessageProcessingService messageProcessingService) {
        this.messageProcessingService = messageProcessingService;
    }

    @JmsListener(destination = "${app.queue.main:message.queue}", concurrency = "1-5")
    public void processMessage(String messageContent,
                              @Header(name = "messageId", required = false) String messageId,
                              Message message) throws JMSException {

        logger.info("开始处理消息 - ID: {}", messageId);
        handleMessageWithRetry(messageId, messageContent,message);
    }

    /**
     * 带重试机制的消息处理方法
     */
    @Retryable(
            value = { Exception.class },            // 需要重试的异常类型
            maxAttemptsExpression = "${app.message.max-retry-count:5}", // 最大重试次数
            backoff = @Backoff(
                    delayExpression = "${app.message.initial-delay-ms:1000}",   // 初始延迟
                    multiplierExpression = "${app.message.backoff-multiplier:2.0}", // 退让倍数
                    maxDelayExpression = "${app.message.max-delay-ms:60000}"    // 最大延迟
            )
    )
    public void handleMessageWithRetry(String messageId, String content, Message message) throws JMSException {
        boolean success = messageProcessingService.processMessage(messageId, content);
        if (!success) {
            logger.warn("消息处理失败 - ID: {}", messageId);
            throw new RuntimeException("处理失败"); // 触发重试
        }else{
            message.acknowledge();
        }
        logger.warn("消息重试成功 - ID: {}", messageId);
    }

    /**
     * 当超过最大重试次数仍然失败时执行
     */
    @Recover
    public void recover(Exception e, String messageId, String content, Message message) throws JMSException {
        logger.error("消息最终处理失败，进入重新投递逻辑 - ID: {}, 原因: {}", messageId, e.getMessage());
    }
}